import os
from ctypes import cast

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget, QApplication, QAbstractItemView, QHeaderView, QTableWidgetItem, QMessageBox, \
    QDialog
from PyQt5.QtCore import pyqtSignal, Qt
import sys
import traceback
from _ctypes import POINTER

from MVSCam.CameraParams_const import MV_GIGE_DEVICE, MV_USB_DEVICE
from MVSCam.CameraParams_header import MV_CC_DEVICE_INFO_LIST, MV_CC_DEVICE_INFO
from ClientUi.deviceManager.dev_config import max_camera_num, global_camera_type


def search_HK_Cam():
    camera_info_list = []
    try:
        deviceList = MV_CC_DEVICE_INFO_LIST()
        tlayerType = MV_GIGE_DEVICE | MV_USB_DEVICE
        from MVSCam.MvCameraControl_class import MvCamera
        # ch:枚举设备 | en:Enum device
        ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
        if ret != 0:
            print("enum devices fail! ret[0x%x]" % ret)
            return camera_info_list

        print("Find %d devices!" % deviceList.nDeviceNum) 

        for i in range(0, deviceList.nDeviceNum):
            caminfo = []
            mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(
                MV_CC_DEVICE_INFO)).contents
            if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE:
                
                strModeName = ""
                for per in mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName:
                    strModeName = strModeName + chr(per)
                print("device model name: %s" % strModeName)
                caminfo.append(strModeName)
                nip1 = (
                    (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
                nip2 = (
                    (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
                nip3 = (
                    (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
                nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
                print("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
                caminfo.append(f'{nip1}.{nip2}.{nip3}.{nip4}')
            elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
                print("\nu3v device: [%d]" % i)
                strModeName = ""
                for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName:
                    if per == 0:
                        break
                    strModeName = strModeName + chr(per)
                print("device model name: %s" % strModeName)
                caminfo.append(strModeName)
                strSerialNumber = ""
                for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber:
                    if per == 0:
                        break
                    strSerialNumber = strSerialNumber + chr(per)
                print("user serial number: %s" % strSerialNumber)
                caminfo.append(strSerialNumber)

            camera_info_list.append(caminfo)
    except Exception as e:
        print(f'main {e} {traceback.format_exc()}')
    
    return camera_info_list


class Ui_search_camera(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.setFixedSize(642, 400)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(10, 10, 81, 21))
        self.label.setObjectName("label")
        self.cameraname_lb = QtWidgets.QLabel(Form)
        self.cameraname_lb.setGeometry(QtCore.QRect(100, 10, 72, 21))
        self.cameraname_lb.setObjectName("cameraname_lb")        
        self.camerainfo_tablewidget = QtWidgets.QTableWidget(Form)
        self.camerainfo_tablewidget.setGeometry(QtCore.QRect(10, 55, 621, 260))
        self.camerainfo_tablewidget.setObjectName("camerainfo_tablewidget")
        self.camerainfo_tablewidget.setColumnCount(0)
        self.camerainfo_tablewidget.setRowCount(0)
        self.searchcamera_btn = QtWidgets.QPushButton(Form)
        self.searchcamera_btn.setGeometry(QtCore.QRect(10, 340, 80, 36))
        self.searchcamera_btn.setObjectName("searchcamera_btn")
        self.ok_btn = QtWidgets.QPushButton(Form)
        self.ok_btn.setGeometry(QtCore.QRect(552, 340, 80, 36))
        self.ok_btn.setObjectName("ok_btn")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "搜索相机"))
        self.label.setText(_translate("camera_params_setting", "当前相机:"))
        self.cameraname_lb.setText(_translate("camera_params_setting", "相机1"))        
        self.searchcamera_btn.setText(_translate("Form", "搜索"))
        self.ok_btn.setText(_translate("Form", "确定"))

class search_camera_wnd(QDialog, Ui_search_camera):
    selected_cam_signal = pyqtSignal(list)
    def __init__(self,camidx = -1,camtype=0,parent=None):
        super(search_camera_wnd,self).__init__(parent)
        self.setupUi(self)
        currentPath = os.path.abspath(__file__)
        path = os.path.dirname(currentPath)
        clientUiPath = os.path.dirname(path)
        self.setWindowIcon(QIcon(f'{clientUiPath}\\images\\icon.ico'))  # 设置窗口图标
        self.setWindowTitle('相机搜索')

        self.camidx =  camidx 
        self.camtype = camtype
        self.ok_btn.clicked.connect(self.updateparams)
        self.searchcamera_btn.clicked.connect(self.searchcamera)

        # 禁止双击编辑
        self.camerainfo_tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)        
        self.camerainfo_tablewidget.setShowGrid(True)
        self.camerainfo_tablewidget.setGridStyle(QtCore.Qt.DashLine)
        column_labels = []
        column_labels += ['相机','设备名','IP/序列号']

        self.camerainfo_tablewidget.setColumnCount(len(column_labels))
        # self.tableWidget.setRowCount(5000)
        self.camerainfo_tablewidget.setHorizontalHeaderLabels(column_labels)  

        # 设置每一行高度最小
        self.camerainfo_tablewidget.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

        self.camerainfo_tablewidget.setSelectionMode(QAbstractItemView.SingleSelection)
        self.camerainfo_tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        # 设置每一列的宽度
        self.camerainfo_tablewidget.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.camerainfo_tablewidget.horizontalHeader().resizeSection(0, 100)
        self.camerainfo_tablewidget.horizontalHeader().resizeSection(1, 150)
        self.camerainfo_tablewidget.horizontalHeader().resizeSection(2, 200)
        self.camerainfo_tablewidget.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)

        self.init_data()    
        # 禁用最大化按钮
        self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowMaximizeButtonHint)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)

    def init_data(self):
        if self.camidx >= 0 and self.camidx < max_camera_num:
            self.cameraname_lb.setText(f'相机{self.camidx+1}')
            self.searchcamera()
        else:
            self.cameraname_lb.setText(f'---')
                
    def searchcamera(self):
        ['海康相机','大恒相机','度申相机','迈德威视相机','Dalsa相机','通用USB相机','模拟相机','网络相机']
        if self.camtype >= 0 and self.camtype < len(global_camera_type):
            cam_type = global_camera_type[self.camtype] 
            cam_info = None
            if cam_type == '海康相机':
                cam_info = search_HK_Cam()
            elif cam_type == '大恒相机':
                pass
            elif cam_type == '度申相机':
                pass
            elif cam_type == '迈德威视相机':
                pass
            elif cam_type == 'Dalsa相机':
                pass
            elif cam_type == '通用USB相机':
                pass
            elif cam_type == '模拟相机':
                pass
            elif cam_type == '网络相机':
                pass 

            if cam_info != None:
                self.camerainfo_tablewidget.clearContents()
                self.camerainfo_tablewidget.setRowCount(0)
                for info in cam_info:
                    if len(info) >= 2:
                        self.add_table_row(info)
    # 添加一行表格数据
    def add_table_row(self, row_data):
        rownum = self.camerainfo_tablewidget.rowCount()
        self.camerainfo_tablewidget.insertRow(rownum)
        camitem = QTableWidgetItem(f'相机{rownum+1}')
        self.camerainfo_tablewidget.setItem(rownum, 0, camitem)
        for column in range(len(row_data)):
            item = QTableWidgetItem(str(row_data[column]))
            self.camerainfo_tablewidget.setItem(rownum, column+1, item)                                                                                
    def set_camera_info(self,camidx,camtype):
        self.camidx = camidx
        self.camtype = camtype
        self.init_data()

    def updateparams(self):
        if self.camidx >= 0 and self.camidx < max_camera_num:
            selected_items = self.camerainfo_tablewidget.selectedItems()
            if not selected_items:
                # self.selected_cam_signal.emit(['192.168.2.2'])
                QMessageBox.warning(self, 'Warning', '未选择任何相机!')
                return

            # 假设每行只有一个单元格被选中
            selected_row_index = selected_items[0].row()
            row_data = []
            for col in range(self.camerainfo_tablewidget.columnCount()):
                if col == 2:
                    item = self.camerainfo_tablewidget.item(selected_row_index, col)
                    if item:
                        row_data.append(item.text())
                    else:
                        row_data.append('')

            # 打印选中的行数据
            print(f"Selected row data: {row_data}")  

            if len(row_data) > 0:
                self.selected_cam_signal.emit(row_data)
        self.accept()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    try:
        current_path = os.path.abspath(__file__)
        path = os.path.dirname(current_path)
        path = os.path.dirname(path)
        app.setStyleSheet(open(f'{path}/styleSheet.qss', encoding='utf-8').read())
        window = search_camera_wnd()
        window.showNormal()
        sys.exit(app.exec_())

    except Exception as e:
        print(e)  